<?php
require_once 'config.php'; 
require_once 'startup.php'; 

require_once APP_DIR . 'mail.php'; 
require_once APP_DIR . 'phpmailer/class.phpmailer.php'; 
require_once APP_DIR . 'phpmailer/class.pop3.php'; 
require_once APP_DIR . 'phpmailer/class.smtp.php'; 

// Check for user login
if(!$user->isLogged()){ 
    header('Location: ' . $config['url_admin'] . 'login.php');    
    exit();
}

// Render index page
$page_title = 'Havhokeren - Administration';
$title = 'Send newsletter';

$logged = $user->getUserName();
$cancel = $config['url_admin'] . 'index.php';
$logout = $config['url_admin'] . 'logout.php';     
$edit_user = $config['url_admin'] . 'changepassword.php';
$send_newsletter = 'javascript:void(0);';
$continue = $config['url_admin'] . basename(__FILE__);
$subscriber = $config['url_admin'] . 'index.php'; 

$text_send = 'Send';
$text_cancel = 'Cancel';
$text_logout = 'Logout';
$text_edit_user = 'Change password';
$text_subscriber = 'Subscribers';
$text_newsletter = 'Newsletter';
$text_email = 'Email address';
$text_date = 'Date register';
$text_goback = 'Click here to go back to subscribers list!';
$text_from = 'From';
$text_to = 'To'; 
$text_subject = 'Subject';
$text_message = 'Message';
$text_continue = 'Continue';

$item_send = false;  
$image_path = $config['url_admin'] . 'filemanager.php';

// Get data to insert, edit or delete
$from       = isset($request->post['from']) ? $request->post['from'] : '';
$from_name  = isset($request->post['from_name']) ? $request->post['from_name'] : '';
$to         = isset($request->post['to']) ? $request->post['to'] : '';
$subject    = isset($request->post['subject']) ? $request->post['subject'] : '';
$message    = isset($request->post['message']) ? $request->post['message'] : '';    
$message    = str_replace('\\"', '"', html_entity_decode($message, ENT_QUOTES, 'UTF-8')); 

$query = $db->query("SELECT * FROM " . DB_PREFIX . "newsletter");
foreach($query->rows as $row){
    $subscribers[] = array(
        'email' => $row['email'],
        'date'  => strftime('%d-%m-%Y', strtotime($row['date_added'])),
        'name'  => $row['name'],
    );    
}        
 
$validate_error = array();    
if($request->server['REQUEST_METHOD'] == 'POST' && isset($request->post)){   
    $validate_error = validate($request);   
    
    if(empty($validate_error)) { 
        $message_body  = '<html dir="ltr" lang="en">' . "\n";
        $message_body .= '<head>' . "\n";
        $message_body .= '<title>' . $request->post['subject'] . '</title>' . "\n";
        $message_body .= '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' . "\n";
        $message_body .= '</head>' . "\n";
        //$message_body .= '<body>' . html_entity_decode($message, ENT_QUOTES, 'UTF-8') . '</body>' . "\n";        
        $message_body .= '<body>' . $message . '</body>' . "\n";        
        $message_body .= '</html>' . "\n";
        
        $attachments = array();
        if(preg_match_all('#(src="([^"]*)")#mis', $message_body, $matches)){              
            foreach ($matches[2] as $key => $value) {
                $filename = md5($value) . strrchr($value, '.');
                $path = rtrim($request->server['DOCUMENT_ROOT'], '/') . parse_url($value, PHP_URL_PATH);
                        
                $attachments[] = array(
                    'filename' => $filename,
                    'path'     => $path
                );
                        
                $message_body = str_replace($value, 'cid:' . basename($filename), $message_body);
            }              
        } 
        //print('<pre>');
        //print_r($attachments); 
        $emails = $request->post['to']; 
        foreach ($emails as $email){
            sendMail($email, $attachments, $message_body, false);    
        } 
        
        $success = 'Newsletter has been sent to selected list.';
        unset($error);
        $item_send = true;  
        //$send_newsletter = $config['url_admin'] . basename(__FILE__);
    }
    else{
        reset($validate_error);
        $error = current($validate_error);
        unset($success);        
    }
}    

// Render page
include_once 'header.php';
?>

<?php
function sendMail($email, $attachments, $message, $use_phpmailer = true){
    global $config, $request;
    
    if($use_phpmailer){
        $mail = new PHPMailer(true);  
        try{
            if($config['mail_protocol'] == 'mail'){
                $mail->IsMail();
            }
            else{
                $mail->IsSMTP();
                $mail->Host       = $config['smtp_host'];   
                $mail->SMTPDebug  = 2;                      // enables SMTP debug information (for testing)                               
                $mail->SMTPAuth   = true;            
                $mail->Port       = $config['smtp_port'];
                $mail->Username   = $config['smtp_username'];  
                $mail->Password   = $config['smtp_password'];           
                if(stristr('gmail', $config['smtp_host'])){
                    $mail->SMTPSecure = "ssl";    
                }
            }
            $mail->AddReplyTo($request->post['from'], $request->post['from_name']);
            $mail->AddAddress($request->post['from'], $request->post['from_name']);
            $mail->SetFrom($request->post['from'], $request->post['from_name']);
            $mail->Subject = $request->post['subject'];        
            $mail->MsgHTML($message);
            foreach ($attachments as $attachment) {
                if(file_exists($attachment['path'])){
                    $mail->AddAttachment($attachment['path']);
                }                
            }

            $mail->Send();    
        }
        catch (phpmailerException $e){
            echo $e->errorMessage(); 
        } 
        catch (Exception $e) {
            echo $e->getMessage(); 
        }
    }
    else{
        $mail = new Mail();
        $mail->protocol     = $config['mail_protocol'];
        $mail->parameter    = $config['mail_parameter'];
        $mail->hostname     = $config['smtp_host'];
        $mail->username     = $config['smtp_username'];
        $mail->password     = $config['smtp_password'];
        $mail->port         = $config['smtp_port'];
        $mail->timeout      = $config['smtp_timeout'];   
                                      
        $mail->setFrom($request->post['from']);             
        $mail->setTo($email);        
        $mail->setSender($request->post['from_name']);        
        $mail->setSubject($request->post['subject']);
        foreach ($attachments as $attachment) {
            if(file_exists($attachment['path'])){
                $mail->addAttachment($attachment['path'], $attachment['filename']);
            }            
        }
        $mail->setHtml($message);
        $mail->send();        
    }
}

function validate($request){
    $error = array();
    $pattern = '/^[A-Z0-9._%-+]+@[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z]{2,6}$/i';         
    
    if(!$request->post['from']){
        $error['from'] = 'Please enter a from email';
    }
    
    if(!$request->post['to'] || empty($request->post['to'])){
        $error['to'] = 'Please select email to send';
    }
    
    if(!$request->post['subject']){
        $error['subject'] = 'Please enter a subject';
    }

    if (!$request->post['message']) {
        $error['message'] = 'Please enter a message';
    }
                        
    return $error;
}    
?>

<script type="text/javascript"><!--
    jQuery(document).ready(function(){
        var editor = CKEDITOR.replace('message', {
            filebrowserBrowseUrl: '<?php echo $image_path; ?>',
            filebrowserImageBrowseUrl: '<?php echo $image_path; ?>',
            filebrowserFlashBrowseUrl: '<?php $image_path; ?>',
            filebrowserUploadUrl: '<?php echo $image_path; ?>',
            filebrowserImageUploadUrl: '<?php $image_path; ?>',
            filebrowserFlashUploadUrl: '<?php $image_path; ?>',
        });         
        
        jQuery(".scrollbox").each(function(i){
            jQuery(this).attr('id', 'scrollbox_' + i);
            sbox = '#' + jQuery(this).attr('id');
            jQuery(this).after('<span><a onclick="$(\'' + sbox + ' :checkbox\').attr(\'checked\', \'checked\');"><u>Select All</u></a> / <a onclick="$(\'' + sbox + ' :checkbox\').attr(\'checked\', \'\');"><u>Unselect All</u></a></span>');
        });        
        
        jQuery('#send_newsletter').click(function(even){
            even.preventDefault(); 
            
            jQuery('#newsletter_form').submit();
        });
    });  
//-->
</script>

<body>
    <div id="header">
        <div class="div1"><img style="cursor: pointer;" src="<?php echo $config['url_admin']; ?>image/logo.png" title="<?php echo $title; ?>" onclick="location = '<?php echo $config['url_admin']; ?>'" /></div>
        <?php if ($logged) { ?>
            <div class="div2"><img src="<?php echo $config['url_admin']; ?>image/lock.png" alt="" style="position: relative; top: 3px;" />You are logged in as: &nbsp;<?php echo $logged; ?></div>
        <?php } ?>
    </div>
    
    <?php if ($logged) { ?>
        <div id="menu">
            <ul class="nav left" style="display: block;">
                <li id="subscriber"><a class="top" href="<?php echo $subscriber; ?>"><?php echo $text_subscriber; ?></a></li>
                <li id="newsletter" class="selected"><a class="top" href="<?php echo $send_newsletter; ?>"><?php echo $text_newsletter; ?></a></li>                
            </ul>
            <ul class="nav right">                
                <li id="edit_user"><a class="top" href="<?php echo $edit_user; ?>"><?php echo $text_edit_user; ?></a></li>
                <li id="logout"><a class="top" href="<?php echo $logout; ?>"><?php echo $text_logout; ?></a></li>
            </ul>
        </div>
    <?php } ?>
    
    <div id="content">
        <div class="breadcrumb"></div>
        
        <?php if(isset($error)) { ?> 
            <div class="warning"><?php echo $error; ?></div>
        <?php } ?>
        <?php if(isset($success)){ ?>
            <div class="success"><?php echo $success;?></div>
        <?php } ?>
    
        <div class="box">
            <div class="left"></div>
            <div class="right"></div>
            <div class="heading">
                <h1 style="background-image: url('<?php echo $config['url_admin']; ?>image/newsletter.png');"><?php echo $title; ?></h1>
                <div class="buttons">
                     <?php if(!$item_send){ ?>
                        <a id="send_newsletter" href="<?php echo $send_newsletter; ?>" class="button"><span><?php echo $text_send; ?></span></a>
                        <a onclick="location = '<?php echo $cancel; ?>'" class="button"><span><?php echo $text_cancel; ?></span></a>
                     <?php }else{ ?>
                        <a onclick="location = '<?php echo $continue; ?>'" class="button"><span><?php echo $text_continue; ?></span></a>
                     <?php } ?>
                </div>
            </div>
            
            <div class="content">      
                <form id="newsletter_form" action="<?php echo $config['url_admin'] . basename(__FILE__); ?>" method="post" enctype="multipart/form-data">
                    <table class="form">                         
                        <tbody>
                            <?php if(!$item_send){ ?>
                                <tr>
                                    <td><?php echo $text_from; ?></td>
                                    <td>
                                        <?php echo $config['name'] . ' &lt;' . $config['email'] . '&gt;'; ?>
                                        <input type="hidden" name="from" value="<?php echo $config['email']; ?>" />
                                        <input type="hidden" name="from_name" value="<?php echo $config['name']; ?>" />                                        
                                    </td>
                                </tr>  
                                <tr>
                                    <td><?php echo $text_to; ?><span class="required">*</span></td>
                                    <td>
                                        <div class="scrollbox">
                                            <?php $class = 'odd'; ?>
                                            <?php foreach ($subscribers as $item) { ?>
                                                <?php $class = ($class == 'even' ? 'odd' : 'even'); ?>
                                                <?php if(!empty($to)) { ?>
                                                    <?php $checked = in_array($item['email'], $to) ? 'checked="checked"' : ''; ?>
                                                <?php } ?>
                                                <div class="<?php echo $class; ?>">
                                                    <input type="checkbox" name="to[]" value="<?php echo $item['email']; ?>" <?php echo $checked; ?> />
                                                    <?php echo $item['email']; ?>
                                                </div>
                                            <?php } ?>
                                        </div>
                                    </td>
                                </tr>                                                        
                                <tr>
                                    <td><?php echo $text_subject; ?><span class="required">*</span></td>
                                    <td><input name="subject" value="<?php echo $subject; ?>" size="100" /></td>                                
                                </tr>
                                <tr>
                                    <td><?php echo $text_message; ?><span class="required">*</span></td>
                                    <td><textarea name="message" id="message"><?php echo $message; ?></textarea></td>                                
                                </tr>  
                            <?php }else{ ?>
                                <tr>
                                    <td align="center" colspan="2"><a href="<?php echo $cancel; ?>"><?php echo $text_goback; ?></a></td>
                                </tr>
                            <?php } ?>                         
                        </tbody>
                    </table>   
                </form>                    
            </div>
        </div>
    </div>
    
    <?php include_once 'footer.php'; ?>
</body>
</html>
